package com.itheima.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.common.constant.MessageConstant;
import com.itheima.common.entity.PageResult;
import com.itheima.common.entity.QueryPageBean;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.pojo.dto.CheckGroupDTO;
import com.itheima.pojo.vo.CheckGroupVO;
import com.itheima.service.CheckGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.beans.Transient;
import java.util.List;

@Service
public class CheckGroupServiceImpl implements CheckGroupService {
	@Autowired
	private CheckGroupMapper checkGroupMapper;

	@Transactional//开启事务，只有检查组 和 检查项 的关联关系全部插入才成功
	@Override
	public void add(CheckGroupDTO checkGroupDTO, String checkItemIds) {
		//插入检查组,并获得检查组ID
		checkGroupMapper.insertGroup(checkGroupDTO);
		Integer groupId = checkGroupDTO.getId();
		//插入检查组和检查项的关联关系
		String[] ids = checkItemIds.split(",");
		for (String id : ids) {
			checkGroupMapper.insertAssociation(groupId, id);
		}

	}

	@Override
	@Transactional
	public void delete(String checkGroupId) {
		//首先确认检查组是否被套餐包含 ，如果包含则不允许删除
		List<Long> setmealIds = checkGroupMapper.getSetmealByGroupId(checkGroupId);
		if (setmealIds.size() > 0 && setmealIds != null) {
			throw new RuntimeException(MessageConstant.DELETE_CHECKGROUP_FAIL);
		}
		//删除检查组与检查项的关联关系
		checkGroupMapper.deleteAssociation(checkGroupId);
		//删除检查组
		checkGroupMapper.delete(checkGroupId);
	}

	@Override
	public void edit(CheckGroupDTO checkGroupDTO, String checkItemIds) {
		//更新关系表
		if (checkItemIds != null && !checkItemIds.equals("")) {
			//先删除原有的关系
			checkGroupMapper.deleteAssociation(checkGroupDTO.getId() + "");
			//创建新的关系
			for (String id : checkItemIds.split(",")) {
				checkGroupMapper.insertAssociation(checkGroupDTO.getId(), id);
			}
		}
		//更新检查组数据
		checkGroupMapper.updateGroup(checkGroupDTO);
	}

	@Override
	public PageResult findPage(QueryPageBean checkGroupDTO) {
		PageHelper.startPage(checkGroupDTO.getCurrentPage(), checkGroupDTO.getPageSize());
		Page<CheckGroupDTO> page = checkGroupMapper.getPage(checkGroupDTO);
		long total = page.getTotal();
		List<CheckGroupDTO> rows = page.getResult();
		return new PageResult(total, rows);

	}

	@Override
	public CheckGroupDTO findById(String checkGroupId) {
		CheckGroupDTO checkGroupDTO = checkGroupMapper.findById(checkGroupId);
		return checkGroupDTO;
	}

	@Override
	public List<CheckGroupVO> findAll() {
		List<CheckGroupVO> checkGroupVOList = checkGroupMapper.findAll();
		return checkGroupVOList;
	}

	@Override
	public List<Integer> findCheckGroupIdsBySetmealId(Integer setmealId) {
		List<Integer> checkGroupIds = checkGroupMapper.findCheckGroupIdsBySetmealId(setmealId);
		return checkGroupIds;
	}

}
